// 文件上传组件
import React,{useState} from "react"
import {useStore} from "../stores/index"
import {observer} from "mobx-react"
import { InboxOutlined } from '@ant-design/icons';
import { Upload, message,Spin} from 'antd';
import styled from "styled-components"

const Ul = styled.ul`
  list-style:none;
  li{
    font-size:18px;
    padding-bottom:5px;
    img{
      width:200px
    }
  }
`


const Component =observer(()=>{
  const { Dragger } = Upload;
  const {ImageStore,UserStore} = useStore()
  const [fileList, setFileList] = useState([]);
  const [fileDate,setFileDate] = useState({})
  const bindChange = (files,name)=>{
    // if(ref.current.files.length > 0){
      ImageStore.setFile(files)
      ImageStore.setFilename(name)
      ImageStore.upload().then((response)=>{
        console.log("上传成功",response)
        setFileDate({...response.attributes.url.attributes})
      }).catch((error)=>{
        console.log("上传失败",error)
      })
    // }
  }
  const props = {
    name: 'file',
    maxCount:1,
    multiple:false,
    showUploadList:false,
    action: '',
    onChange(info) {
      console.log("change",info.file)
      setFileDate({})
      if(!UserStore.currentUser){
        message.error('请登录后上传');
        return
      }
      if(!/(svg$)|(png$)|(jpg$)|(jpeg$)|(gif$)/ig.test(info.file.type)){
        message.error('只支持图片类型为：svg、png、jpg、jpeg、gif格式的图片');
        return
      }
      if(info.size > 1024*1024){
        message.error('文件大小不能超过1MB');
        return
      }
      
      bindChange(info.file,info.file.name)
    },
    onDrop(e) {
      console.log('onDrop', e.dataTransfer.files);
      // bindChange(e.dataTransfer.files[0],e.dataTransfer.files[0].name)
    },
    beforeUpload: (file) => {
      setFileList([...fileList, file]);
      return false;
    },
  };

  return (
    <div>
      <Spin tip="正在上传..." spinning={ImageStore.isUploading?true:false}>
        <Dragger {...props}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽上传图片</p>
          <p className="ant-upload-hint">
          只支持图片类型为：svg、png、jpg、jpeg、gif格式的图片,且图片小于1MB
          </p>
        </Dragger>
      </Spin>
      {
        fileDate.name?<>
          <h2>上传列表</h2>
          <Ul>
            <li>文件名称：{fileDate.name}</li>
            <li>文件类型：{fileDate.mime_type}</li>
            <li>图片地址：{fileDate.url}</li>
            <li>
              <img src={fileDate.url} alt="" />
            </li>
          </Ul>
        </>:<></>
      }
    </div>
  )
})

export default Component